package com.audaque.springboot.foshanupload.web.filter;

/**
 * @author zgb
 * @desc ...
 * @date 2022-02-02 01:29:23
 */

import cn.hutool.json.*;
import com.audaque.springboot.foshanupload.core.util.StringUtils;
import com.audaque.springboot.foshanupload.web.wrapper.BodyHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 参数校验过滤器（针对json报文请求） 1.获取请求参数；2.对获取到的请求参数进行处理（解密、字符串替、请求参数分类截取等等）；3.把处理后的参数放回到请求列表里面
 *
 * @author zhaoheng
 */
@Slf4j
//@Component
public class BodyConvertFilter implements Filter {

    public String convert(String target) {
        log.debug("编码转换之前：" + target);
        try {
            String s = new String(target.trim().getBytes("ISO-8859-1"), "UTF-8");
            log.debug("编码转换之后：" + s);
            return s;
        } catch (UnsupportedEncodingException e) {
            return target;
        }
    }

    @Override
    public void destroy() {
        log.debug("过滤器执行结束");
    }
    private void logThread(){
        log.debug("ThreadId:" + Thread.currentThread().getId());
        log.debug("ThreadName:" + Thread.currentThread().getName());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String url0 = httpServletRequest.getRequestURI();
        String url1 = httpServletRequest.getContextPath();
        log.debug("完整地址：" + url0);
        log.debug("返回当前页面所在的应用的名字：" + url1);
        
        logThread();
      //int i=1/0;
        // 获取请求地址
        String url = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length());
        log.debug("controllerUrl：" + url);
        String method = httpServletRequest.getMethod();
        log.debug("method：" + method);

        if(!Objects.equals(method,"POST")){
            chain.doFilter(request, response);
            //放行后一定要return,否则有多个放行代码时会发起多个请求
            return;
        }
        String header = httpServletRequest.getHeader("Content-Type");
        if(header!=null&&!header.toLowerCase().contains("json")){
            chain.doFilter(request, response);
            //放行后一定要return,否则有多个放行代码时会发起多个请求
            return;
        }


        //处理json报文请求
        BodyHttpServletRequestWrapper requestWrapper = new BodyHttpServletRequestWrapper(httpServletRequest);
        // 读取请求内容
        BufferedReader br;
        br = requestWrapper.getReader();
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        // 将json字符串转换为json对象
        String s = sb.toString();
        if(StringUtils.isNotBlank(s)){
            JSONConfig jsonConfig = JSONConfig.create();
            jsonConfig.setIgnoreNullValue(false);
            jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
            JSON json = JSONUtil.parse(s, jsonConfig);
            String result = null;
            if(json instanceof JSONObject){
                Map<String, Object> map = new HashMap<String, Object>();
                // 把json对象转换为Map集合
                map = JSONUtil.toBean((JSONObject)json, Map.class);
                map.forEach((k,v)->{
                    log.debug("k:"+k);
                    log.debug("v:"+v);
                    if (v != null) {
                        if (v instanceof String[]) {
                            Arrays.stream((String[]) v).forEach(e->this.convert(e));
                        } else if (v instanceof String) {
                            this.convert((String)v);
                        }
                    }
                });

                // 把参数转换之后放到我们的body里面
                result = JSONUtil.toJsonStr(map);
            }else  if(json instanceof JSONArray){
                List<Map<String, Object>> mapList = new ArrayList<>();
                JSONArray jSONArray= (JSONArray)json;
                for (Object json1 : jSONArray) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    // 把json对象转换为Map集合
                    map = JSONUtil.toBean((JSONObject)json1, Map.class);
                    map.forEach((k,v)->{
                        log.debug("k:"+k);
                        log.debug("v:"+v);
                        if (v != null) {
                            if (v instanceof String[]) {
                                Arrays.stream((String[]) v).forEach(e->this.convert(e));
                            } else if (v instanceof String) {
                                this.convert((String)v);
                            }
                        }
                    });
                    mapList.add(map);
                }
                result = JSONUtil.toJsonStr(mapList);
            }

            requestWrapper.setBody(result.getBytes("UTF-8"));
            ///传递给目标servlet或jsp的实际上时包装器对象的引用，而不是原始的HttpServletRequest对象
            chain.doFilter(requestWrapper, response);
            //放行后一定要return,否则有多个放行代码时会发起多个请求
            return;

        }
        chain.doFilter(requestWrapper, response);
        //放行后一定要return,否则有多个放行代码时会发起多个请求
        return;

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
